package com.heima.filter;

import ch.qos.logback.core.util.StringUtil;
import com.heima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;
//拦截所有请求路径
//@WebFilter(urlPatterns = "/*")

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String url = httpServletRequest.getRequestURL().toString();
        //判断请求中是否包含login,如果包含则放行
        if(url.contains("/login")){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
        //获取请求头中的令牌
        String jwt = httpServletRequest.getHeader("token");
        //token不存在,直接返回401
        if(!StringUtils.hasLength(jwt)){
            httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return ;
        }
        //存在就判断是否合法
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //合法就放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
